import datetime
import random

from flask import session
from flask_script import Manager
from flask_migrate import MigrateCommand
from info import create_app


# 创建web应用
app = create_app("dev")
# 创建管理器

mgr = Manager(app)

# 使用管理器生成迁移命令
mgr.add_command("mc", MigrateCommand)

# 生成管理员账号
@mgr.option("-u",dest = "username")
@mgr.option("-p",dest = "password")
def create_superuser(username,password):
    #　校验参数
    if not all([username,password]):
        app.logger.error("参数不足，生成失败")
        return
    from info.utils.models import User
    from info import db
    user = User()
    user.mobile = username
    user.password = password
    user.nick_name = username
    user.is_admin = True
    db.session.add(user)
    try:
        db.session.commit()
    except BaseException as e:
        app.logger.error("生成失败 : %s" % e)
        db.session.rollback()
        return

    app.logger.error("生成成功")

@mgr.command
def add_test_users():
    """添加测试数据"""
    from info import db
    from info.utils.models import User
    users = []
    now = datetime.datetime.now()  # 取当前时间
    for num in range(0, 10000):
        try:
            user = User()
            user.nick_name = "%011d" % num
            user.mobile = "%011d" % num
            user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829"
            # 随机生成时间  范围: [上个月-本月当前时间]
            user.create_time = now - datetime.timedelta(seconds=random.randint(0, 2678400))
            users.append(user)
            print(user.mobile)
        except Exception as e:
            print(e)
    db.session.add_all(users)
    db.session.commit()
    print('OK')

if __name__ == '__main__':
   # print(app.url_map)
    mgr.run()